<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Constants\UserMoneyLogTypeConstants;
use App\CustHub\Mapper\ChTransferRecordMapper;
use App\CustHub\Vo\UserBalanceVo;
use App\Setting\Service\SettingConfigService;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;
use Mine\Exception\NormalStatusException;
use function Swoole\Coroutine\Http\request;

class ChTransferRecordService extends AbstractService
{
    public $mapper;


    #[Inject]
    protected SettingConfigService $configService;

    public function __construct(
        ChTransferRecordMapper $mapper
    )
    {
        $this->mapper = $mapper;
    }

    public function save(array $data): mixed
    {
        $data['order_no'] = generateOrderNumber();
        return $this->mapper->save($data);
    }

    #[Transaction]
    public function update(mixed $id, array $data): bool
    {
        $info = $this->mapper->model::query()
            ->where('id',$id)
            ->first();
        if($data['status'] == 1){
            $result = container()->get(UserBalanceService::class)->updateBalance(new UserBalanceVo(
                uid: $info->uid,
                money: (float)$info->amount,
                businessType: UserMoneyLogTypeConstants::RECHARGE,
                order_id: $info->id,
                remark: '对公转账'
            ));

            if(!$result){
                throw new NormalStatusException("操作失败，请重试~");
            }
        }
        $data['audit_date'] = Carbon::now();
        return $this->mapper->update($id, $data);
    }

    /**
     * 获取对公转账配置
     * @return array
     */
    public function getCorporateTransferConfig(): array
    {
        $data = $this->configService->getConfigByGroupKey('dg_zz');

        $list = array_column($data,'value','key');
        return $list;
    }
}